<?php
/**
 * Description: 完成任务提交数据
 * User: devforma
 * Date: 15/1/7
 * Time: 12:13
 */

require __DIR__ . '/includes/utils.php';

class FinishTask implements iController {

    private $userIdField, $userId;
    
    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;
        
        //验证并确定求求用户的身份，为0表示验证失败，为1表示正式用户，为2表示游客
        $u = validateUser($queryArgs); 
        if ($u == 0 || empty($queryArgs['task_id']) || !is_numeric($queryArgs['task_id'])) {
            return genOutput(1000);
        }

        if ($u == 1) {
            $this->userIdField = 'user_id';
            $this->userId = $queryArgs['user_id'];
        } elseif ($u == 2) {
            $this->userIdField = 'guest_id';
            $this->userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }
        
        //检测任务状态
        $task = DailyPlanUtils::getMissionRecord($queryArgs['task_id']);
        if (empty($task) || $task->action_type != 0)
            return genOutput(1000);

        $now = date('Y-m-d H:i:s');

        //根据不同的任务类型分别处理
        switch ($task->mission_type) {
            case DailyPlanUtils::MISSIONTYPE_NOTELEARNING: //知识点学习任务
            case DailyPlanUtils::MISSIONTYPE_NOTEREVIEW:   //知识点复习任务
                //答题信息参数校验
                if (empty($queryArgs['data']) || !($data = json_decode($queryArgs['data']))) {
                    return genOutput(1000);
                }

                //解析题目信息
                $content = json_decode($task->mission_content);

                //计算本次做完题的正确率,并保存做题记录到user_tests表
                $currentAccuracy = $this->saveTest(array_merge($data->xq, $data->xh));
                
                //计算最终的正确率
                $accuracy = floatval(number_format($currentAccuracy, 3));

                //更新任务记录
                $uddb->update(
                    $uddb->recentMissionInfo,
                    [
                        'mission_content' => json_encode([
                            'questions' => $data,
                            'average_accuracy' => $content->average_accuracy,
                            'accuracy' => $accuracy,
                            'rate' => $content->rate
                        ]),
                        'action_time' => $now,
                        'action_type' => 1
                    ],
                    ['id' => $queryArgs['task_id']]
                );

                return genOutput(1, ['accuracy' => $accuracy]);

            case DailyPlanUtils::MISSIONTYPE_TEST:      //小测验
            case DailyPlanUtils::MISSIONTYPE_WEEKTEST:  //周测验
                //答题信息参数校验
                if (empty($queryArgs['data']) || !($data = json_decode($queryArgs['data']))) {
                    return genOutput(1000);
                }

                //更新任务记录
                $uddb->update(
                    $uddb->recentMissionInfo,
                    ['mission_content' => $queryArgs['data'], 'action_time' => $now, 'action_type' => 1],
                    ['id' => $queryArgs['task_id']]
                );

                //保存做题记录到user_tests表
                $this->saveTest($data->answers);

                return genOutput(1);

            case DailyPlanUtils::MISSIONTYPE_BEGINNER:  //开启计划任务
                //更新任务记录
                $uddb->update($uddb->recentMissionInfo, ['action_time' => $now, 'action_type' => 1], ['id' => $queryArgs['task_id']]);

                //更新开启计划记录
                $uddb->update($uddb->recentAvMission, ['mission_status' => 1], [$this->userIdField => $this->userId, 'mission_type' => $task->mission_type]);

                return genOutput(1);

            default:
                //更新任务记录
                $uddb->update($uddb->recentMissionInfo, ['action_time' => $now, 'action_type' => 1], ['id' => $queryArgs['task_id']]);
                
                return genOutput(1);
        }
    }

    /**
     * 保存做题数据到test表
     * @param array $data 做题数据数组
     * @return float 本次做题数据的正确率
     */
    private function saveTest($data) {
        global $uddb;
        
        if (empty($data)) return 0.0;

        //获取用户所选考试项目id
        $query = "SELECT `testarea_id` FROM `dp_user_dailyplan_data` WHERE `{$this->userIdField}`=:user";
        $testareaId = $uddb->getVar($query, [':user' => $this->userId]);
        if (empty($testareaId)) return 0.0;
        
        //构造insert字符串
        $now = date('Y-m-d H:i:s');
        $values = array();
        $rightCount = 0;
        foreach ($data as $q) {
            $values[] = sprintf("(%d, %d, %d, '%s', %d, %d, %d, '%s')",
                $this->userId,
                $q->id,
                $q->category,
                $now,
                $q->is_wrong,
                $q->note_id,
                $testareaId,
                $q->answer
            );

            //用于计算正确率
            if (!$q->is_wrong) $rightCount++;
        }
        
        if (!empty($values)) {
            $sql = "INSERT INTO `dp_history_user_tests` (`{$this->userIdField}`, `question_id`, `category_id`, `test_time`, `is_wrong`,`note_id`, `testarea_id`, `user_answer`) VALUES ".implode(',', $values);
            $uddb->query($sql);
        }
        
        return $rightCount/count($data);
    }

}